package com.falm.maker.generator.file;

import cn.hutool.core.util.ObjectUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * @author Administrator
 */
public class DynamicFileGenerator extends FileGenerate{

    private static final Logger log = LoggerFactory.getLogger(DynamicFileGenerator.class);


    @Override
    public void doGenerate(String inputPath, String outputPath) throws IOException {

        // 创建配置
        Template template = getTemplate(inputPath);
        if (ObjectUtil.isEmpty(template)) {
            return;
        }
        // 确保输出文件的父目录存在
        File outputFile = new File(outputPath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            if (!parentDir.mkdirs()) {
                throw new IOException(STR."无法创建输出目录: \{parentDir.getAbsolutePath()}");
            }
        }

        try (Writer out = new FileWriter(outputPath)) {
            template.process(dataModel, out);
        } catch (Exception e) {
            log.error("生成文件失败: {}", e.getMessage(), e);
            throw new IOException("生成文件失败", e);
        }
    }

    private static Template getTemplate(String inputPath) throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        // 设置模板根路径
        File templateFile = new File(inputPath);
        File templateDir = templateFile.getParentFile();
        if (!templateDir.exists()) {
            throw new IOException(STR."模板目录不存在: \{templateDir.getAbsolutePath()}");
        }
        configuration.setDirectoryForTemplateLoading(templateDir);
        // 设置编码
        configuration.setDefaultEncoding("UTF-8");

        // 获取模板

        return configuration.getTemplate(templateFile.getName());
    }
}